package com.example.administrator.myapplication.set.PersonalCenter;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.myapplication.BmobApplication;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.evaluate.EvaluateMainActivity;
import com.example.administrator.myapplication.evaluate.TestAssess;
import com.example.administrator.myapplication.login.LoginActivity;
import com.example.administrator.myapplication.set.SetMainActivity;
import com.example.administrator.myapplication.set.SetMainFragment;
import com.example.administrator.myapplication.set.UserinfoActivity;
import com.example.administrator.myapplication.tools.History;
import com.example.administrator.myapplication.tools.TestData;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SQLQueryListener;

/**
 * Created by Administrator on 2018/1/16.
 */

public class PersonalCenterTestedFragment extends Fragment{
    private Toolbar toolbar;
    private ImageView custom_headIcon;
    private TextView tv_first_date;
    private TextView tv_second_date;
    private TextView tv_third_date;

    private TextView tv_first_score;
    private TextView tv_second_score;
    private TextView tv_third_score;

    private TextView tv_personcenter_height;
    private TextView tv_personcenter_weight;
    private TextView tv_personcenter_username;
    private String weight;
    private String height;
    private String username;
    private LinearLayout ll_first_score;
    private LinearLayout ll_second_score;
    private LinearLayout ll_third_score;
    private List<History> list;
    private BmobApplication apps;
    private String id;
    private Intent intent;

    private ImageView iv_personlInfo;
    private ImageView iv_person_logout;

    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            //子线程刷新ui
            super.handleMessage(msg);
            if(msg.what==1) {
                //先让集合进行清空
                apps.list.clear();
                int j=3;
                int count =list.size();
                for(int i=0;i<list.size();i++){
                    if(j<=0)
                       break;
                    History history =list.get(list.size()-1-i);
                    apps.list.add(history);
                    j--;
                }

                //------------------------------
                if(count==0){

                    ll_first_score.setVisibility(View.INVISIBLE);
                    ll_second_score.setVisibility(View.INVISIBLE);
                    ll_third_score.setVisibility(View.INVISIBLE);
                }else if(count==1){
                    tv_first_date.setText(apps.list.get(0).getCreatedAt());
                    tv_first_score.setText(apps.list.get(0).getTotal());

                    ll_second_score.setVisibility(View.INVISIBLE);
                    ll_third_score.setVisibility(View.INVISIBLE);
                }else if(count==2){
                    tv_first_date.setText(apps.list.get(0).getCreatedAt());
                    tv_first_score.setText(apps.list.get(0).getTotal());

                    tv_second_date.setText(apps.list.get(1).getCreatedAt());
                    tv_second_score.setText(apps.list.get(1).getTotal());
                    ll_third_score.setVisibility(View.INVISIBLE);
                }else if(count>=3){
                    tv_first_date.setText(apps.list.get(0).getCreatedAt());
                    tv_first_score.setText(apps.list.get(0).getTotal());

                    tv_second_date.setText(apps.list.get(1).getCreatedAt());
                    tv_second_score.setText(apps.list.get(1).getTotal());

                    tv_third_date.setText(apps.list.get(2).getCreatedAt());
                    tv_third_score.setText(apps.list.get(2).getTotal());

                }
            }
            else if(msg.what==2){
                tv_personcenter_height.setText(height+"cm");
                tv_personcenter_weight.setText(weight+"Kg");
                tv_personcenter_username.setText(username);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_personalcenter_tested,container,false);
        init(view);

        new Thread(){
            public void run(){
                query();
            }
        }.start();
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_personcenter);
        toolbar.setNavigationIcon(R.mipmap.custom_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        ll_first_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent =new Intent(getActivity(), EvaluateMainActivity.class);
                intent.putExtra("historykey",0);
                startActivity(intent);
            }
        });

        ll_second_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent =new Intent(getActivity(), EvaluateMainActivity.class);
                intent.putExtra("historykey",1);
                startActivity(intent);
            }
        });
        ll_third_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent =new Intent(getActivity(), EvaluateMainActivity.class);
                intent.putExtra("historykey",2);
                startActivity(intent);
            }
        });


        iv_personlInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getActivity(), UserinfoActivity.class);
                startActivity(intent);
            }
        });

        iv_person_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
                intent =new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });

        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.testmenu,menu);
    }

    public void init(View view){
        tv_first_date= (TextView) view.findViewById(R.id.tv_first_history_date);
        tv_second_date= (TextView) view.findViewById(R.id.tv_second_history_date);
        tv_third_date= (TextView) view.findViewById(R.id.tv_third_history_date);
        tv_first_score= (TextView) view.findViewById(R.id.tv_first_history_score);
        tv_second_score= (TextView) view.findViewById(R.id.tv_second_history_score);
        tv_third_score= (TextView) view.findViewById(R.id.tv_third_history_score);
        tv_personcenter_height= (TextView) view.findViewById(R.id.tv_personcenter_height);
        tv_personcenter_weight= (TextView) view.findViewById(R.id.tv_personcenter_weight);
        tv_personcenter_username= (TextView) view.findViewById(R.id.tv_personcenter_username);
        ll_first_score= (LinearLayout) view.findViewById(R.id.ll_first_history);
        ll_second_score= (LinearLayout) view.findViewById(R.id.ll_second_history);
        ll_third_score= (LinearLayout) view.findViewById(R.id.ll_third_history);
        iv_personlInfo = (ImageView) view.findViewById(R.id.iv_person_info);
        iv_person_logout= (ImageView) view.findViewById(R.id.iv_person_logout);
        apps= (BmobApplication) getActivity().getApplication();
    }

    public void query(){
	    //从文件中获取objectedid
        File file =new File(getActivity().getFilesDir(),"objectid.txt");
        try {
            BufferedReader br =new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            id=br.readLine();
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //测试历史的查询
        String sql ="select count(createdAt),* from History where id = '"+id+"'";
        new BmobQuery<History>().doSQLQuery(sql, new SQLQueryListener<History>(){

            @Override
            public void done(BmobQueryResult<History> result, BmobException e) {
                if(e ==null){
                    list =(List<History>) result.getResults();
                    MyHandler handler =new MyHandler();
                    handler.sendEmptyMessage(1);

                }else{
                    System.out.println("错误码："+e.getErrorCode()+"，错误描述："+e.getMessage());
                }
            }
        });

        //身高，体重的查询
        BmobQuery<TestData>  user =new BmobQuery<TestData>();
        user.getObject(id, new QueryListener<TestData>() {
            @Override
            public void done(TestData testData, BmobException e) {
                height=testData.getHeight();
                weight=testData.getWeight();
                username=testData.getUsername();
                new MyHandler().sendEmptyMessage(2);
            }
        });

    }
    //注销的方法
    public void logout(){
        File file =new File(getActivity().getFilesDir(),"objectid.txt");
        if(file.exists()){
            file.delete();
        }
        //求出分割的位置所在
        int  Seperatenum =getActivity().getFilesDir().getPath().lastIndexOf("/");
        String Seperatepath =getActivity().getFilesDir().getPath().substring(0,Seperatenum);
        String path1 =Seperatepath+"/shared_prefs/bmob_sp.xml";
        String path2 =Seperatepath+"/shared_prefs/login.xml";
        File file1 =new File(path1);
        File file2 =new File(path2);
        if(file1.exists()){
            file1.delete();
        }
        if(file2.exists()){
            file2.delete();
        }
    }
}
